package tg

import (
	"log"
	"net/http"
	"net/url"

	"gitee.com/dark.H/go-utils/s"
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

// type Di s.Dict
type TgClient struct {
	Token    string `ini:"token"`
	Proxy    string `ini:"proxy"`
	Id       string
	bot      *tgbotapi.BotAPI
	register s.Dict[string, func(name, msg string) (sendMsg string, ifsend bool)]
}

func NewTgAPI() (t *TgClient) {
	t = new(TgClient)
	t.register = make(s.Dict[string, func(name, msg string) (sendMsg string, ifsend bool)])
	return t
}

func (tg *TgClient) AddHook(key string, do func(name, msg string) (sendMsg string, ifsend bool)) {
	tg.register[key] = do
}

func (tg *TgClient) Start() {
	if tg.Token == "" {
		log.Fatal("must set a token for tg!")
	}
	var bot *tgbotapi.BotAPI
	var err error
	if tg.Proxy != "" {
		url, _ := url.Parse(tg.Proxy)
		client := &http.Client{
			Transport: &http.Transport{
				Proxy: http.ProxyURL(url),
			},
		}
		bot, err = tgbotapi.NewBotAPIWithClient(tg.Token, tgbotapi.APIEndpoint, client)
	} else {
		bot, err = tgbotapi.NewBotAPI(tg.Token)
	}

	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true
	tg.bot = bot
	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)
	// bot.GetChat(tgbotapi)
	for update := range updates {
		if update.Message != nil { // If we got a message
			s.Sprintf("[%s] %s", update.Message.From.UserName, s.Str(update.Message.Text).ANSIUnderline()).Println()
			tg.handle(update)
		}
	}
}

func (tg *TgClient) Reply(msg string, update tgbotapi.Update) {
	msgIn := tgbotapi.NewMessage(update.Message.Chat.ID, msg)
	msgIn.ReplyToMessageID = update.Message.MessageID
	tg.bot.Send(msgIn)
}

func (tg *TgClient) handle(update tgbotapi.Update) {
	msgFrom := update.Message.From.UserName
	msgBody := s.Str(update.Message.Text)
	// update.Message./
	// if strings.HasPrefix()
	if msgBody != "" {
		key, body := msgBody.Cut2(" ")
		tg.register.Each(func(k string, v func(name string, msg string) (sendMsg string, ifsend bool)) {
			if key.Eq(k) {
				if sendMsg, ifsend := v(msgFrom, body.String()); ifsend && sendMsg != "" {
					tg.Reply(sendMsg, update)
				}
			}
		})

	}

}
